// pages/collect/index.js
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    customHeight:getApp().globalData.Custom.top,
    tabsList:[
      {name:'购物车',id:0},
      {name:'收藏',id:1}
    ],
    allPrice:0,
    datas:{},
    activeTabs:{},
    manmualAll:false,
    medicineAll:false,
    landscapeAll:false
  },
  clickTabs(e){
    let id = e.target.dataset.id
    if(id==this.data.activeTabs.id)return
    this.setData({
      activeTabs:this.data.tabsList[id],
      datas:{},
      allPrice:0,
      manmualAll:false,
      medicineAll:false,
      landscapeAll:false
    })
    if(id==0){
      this.getMycollect()  
    }else if(id==1){
      this.getShopcart()  
    }
    
    },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {},
  // 单选
  onChange(e){ 
        let i = e.currentTarget.id //序号
        let type = e.target.dataset.type //类型
        let temp1 = `datas.${type}[${i}].checked` 
        let items = this.data.datas[type][i]
        this.setData({
          [temp1]:!this.data.datas[type][i].checked
        })
       this.changeAll(items.salesPrice,items.quantity,items.checked) 
  },
  //总价的改变 
  // type true加false减
  // price 单价
  // num 数量
  changeAll(price,num,type){
    // console.log((price*num).toFixed(2),type)
    let addPrice =parseFloat((price*num).toFixed(2))
    if(!type){
      addPrice=  Math.abs(addPrice) * -1
    }
    let overPrice =this.data.allPrice + addPrice
    // console.log(overPrice)
    this.setData({
      allPrice:parseFloat(overPrice.toFixed(2))
    })
  },
  //全选
  allChange(e){
    let type = e.currentTarget.dataset.type
    if(this.data.datas[type].length<=0)return wx.showToast({
      title: '暂无藏品',
      icon:'none'
    })
    this.setData({
      [`${type}All`]:!this.data[`${type}All`]
    })
    this.data.datas[type].forEach((v,i)=>{
      if(v.checked!=this.data[`${type}All`]){ //不等于 判断加还是减
        this.changeAll(v.salesPrice,v.quantity,this.data[`${type}All`])
      }
      this.setData({
           [`datas.${type}[${i}].checked`]:this.data[`${type}All`]
       })
    }) 
  },
  //数量改变
  numChange(event){
    let i =  event.currentTarget.dataset.index
    let name =  event.currentTarget.dataset.name
    let item = event.currentTarget.dataset.type
    if(item.checked){
      this.changeAll(item.salesPrice,Math.abs(event.detail-item.quantity),event.detail>item.quantity)
    }
    this.setData({
      [`datas.${name}[${i}].quantity`]:event.detail
    })
    
  },
  //确定下单
  async surePlace(){
    if(!this.data.datas)return
    let dataInfo = {
      'skus':[]
    }
    const handleCheckedItem = (item) => {
      if (item.checked) {
        const newItem = {
          spuId: item.spuId,
          quantity: item.quantity,
          paymentPrice: parseFloat((item.salesPrice*item.quantity).toFixed(2)),
          size:item.size
        };
        dataInfo.skus.push(newItem);
      }
    };
    ['manmual', 'medicine', 'landscape'].forEach((type) => {
      this.data.datas[type].forEach((item) => {
        handleCheckedItem(item);
      });
    });
    // console.log(dataInfo)
    let res = await getApp().api.placeOrder(dataInfo)
    console.log(res)
    if(res.code==506)return wx.showToast({
      title: '库存不足',
      icon:"error"
    })
    if(res.code!=200)return wx.showToast({
      title: res.msg,
      icon:"error"
    })
    Dialog.confirm({
      title: '提示',
      message: '下单成功！前往支付',
    })
      .then(() => {
        this.onShow()
        wx.navigateTo({
          url: '/packageB/pages/orderDetail/index?status=1&id='+res.data,
        })
      })
      .catch(() => {
        // on cancel
        this.onShow()
      });
    // wx.navigateTo({
    //   url: '/packageB/pages/myorder/index?index=1',
    // })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      activeTabs:this.data.tabsList[0],
      datas:{},
      allPrice:0,
      manmualAll:false,
      medicineAll:false,
      landscapeAll:false
    })
    this.getMycollect()
  },
  //获取我的收藏
   async getShopcart(){
    let res = await  getApp().api.getCarts()
      // console.log('获取我的收藏:',res)
      if(res.code!=200)return
     ['manmual', 'medicine', 'landscape'].forEach((type) => {
      res.data[type].forEach((item,i) => {  
        item.picUrls= JSON.parse(item.picUrls.replace(/\'/g,"\""))[0]
        item.yyTimes?res.data[type][i].yyTimes=JSON.parse(item.yyTimes):res.data[type][i].yyTimes=[]
        item.size?res.data[type][i].size=item.size:res.data[type][i].size=''
      });
    });
    this.setData({
      datas:res.data
    })
   },
  //取消或添加收藏
 async clearShopcart(e){
    let i = e.currentTarget.dataset.index //下标位置
    let type = e.currentTarget.dataset.type // 属性名称
    let item = e.currentTarget.dataset.item // 元素
    let data =  {
      collector:"1",
      spuCode:item.spuId
     }
     let res = await getApp().api.postCarts(data)
     if(res.code!=200)return
     let newDatas = this.data.datas[type].slice(); // 复制原始数组
      newDatas.splice(i, 1); // 修改新数组
     this.setData({
      [`datas.${type}`]: newDatas
     })
     wx.showToast({
      title: res.msg,
      icon: 'none',
      duration: 2000
    })   
  },
  //获取我的购物车
  async getMycollect(){
    let res = await  getApp().api.getCollect({kind:''})
    // console.log(res)
    if(res.code!=200)return
     ['manmual', 'medicine', 'landscape'].forEach((type) => {
      res.data[type].forEach((item,i) => { 
        item.picUrls= JSON.parse(item.picUrls.replace(/\'/g,"\""))[0]
        item.yyTimes?res.data[type][i].yyTimes=JSON.parse(item.yyTimes):res.data[type][i].yyTimes=[]
        item.size?res.data[type][i].size=item.size:res.data[type][i].size=''
      });
    });
    // console.log(res.data)
     this.setData({
       datas:res.data
     })
  },
  //取消或者添加购物车
  async clearCollect(e){
    let i = e.currentTarget.dataset.index //下标位置
    let type = e.currentTarget.dataset.type // 属性名称
    let item = e.currentTarget.dataset.item // 元素
    if(this.data.activeTabs.id==1){
      if(item.shoppingCart){//取消购物车
        let result = await getApp().api.clearCollect([item.spuId])
        // console.log(result)
        if(result.code!=200)return  Toast.fail(result.msg);
            wx.showToast({
              title: '已从购物车取消',
              icon: 'none',
              duration: 2000
            })
          this.setData({
            [`datas.${type}[${i}].shoppingCart`]:false,
          })   
   }else{ //添加
    let data = {
      spuId:item.spuId,
      addPrice:item.paymentPrice,
      quantity:1,
      spuName:item.name,
      size:item.size
     }
     let res= await getApp().api.postCollect(data)
     if(res.code!=200)return Toast.fail(res.msg);
    this.setData({
      [`datas.${type}[${i}].shoppingCart`]:true,
    })
    //修改状态
    wx.showToast({
      title: '添加成功',
      icon: 'none',
      duration: 2000
    })
   } 
    }else{
      let result = await getApp().api.clearCollect([item.spuId])
      wx.showToast({
        title: '已从购物车取消',
        icon:'none'
      })
      if(result.code!=200)return
      if(item.checked){ //如果已经勾选 减去价格
        this.changeAll(item.salesPrice,item.quantity,false) 
      }
      let newDatas = this.data.datas[type].slice(); // 复制原始数组
      newDatas.splice(i, 1); // 修改新数组
      // console.log(this.data.datas[type])
      this.setData({
        [`datas.${type}`]: newDatas
      });
    }
    
  },
  //跳转详情
  shopDetail(e){
    if(e.currentTarget.dataset.type){
      wx.switchTab({
        url: '/pages/home/index',
      })
    }else{
      wx.navigateTo({
        url: '/packageA/pages/shopDetail/index?id='+e.currentTarget.dataset.id,
      })
    }
     
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})